from javax.swing import *
import java,javax, string
import thread,threading

try:
	import org.rosuda.JRI.RMainLoopCallbacks
except:
	print "Cannot find Java R bridge"

class TextConsole2:
		i=0
		def __init__(self,desktop):
			self.desktop=desktop
			pass
		
		def rWriteConsole(self,re,text,oType):
			print text

		def rBusy(self,re, which):
			print "rBusy("+which+")";

		def rReadConsole(self,re,prompt,addToHistory):
			pass

		def rShowMessage(self,re, message):
			print "rShowMessage \""+message+"\"";

		def rChooseFile(self,re, newFile):
			pass

		def rFlushConsole(self,re):
			pass

		def rLoadHistory(self,re,filename):
			pass

		def rSaveHistory(self,re,filename):
			pass


def RMA_By_Dir(desktop):
	try:
		import org.rosuda.JRI.RMainLoopCallbacks
	except:
		print "cannot find JAVA-R bridge"
		return
	y = TextConsole2(desktop)
	x  = JInternalFrame('Loading RInterpreter')
	desktop.add(x)
	x.show()
	fc = JFileChooser()
	x.getContentPane().add(fc)
	fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
	returnVal = fc.showOpenDialog(x);
	x.pack()
	x.show()
	rFile=''
	if returnVal == JFileChooser.APPROVE_OPTION:
		rFile = fc.getSelectedFile().getAbsolutePath()
	else:
		return None
	x.dispose()
	rFileC = string.replace(rFile, '\\', '/')
	print "Loading files ", rFileC
	# check that affy lib is installed.. if not load
 	me = org.rosuda.JRI.Rengine(None,False,y)
	me.eval("library(affy)")

	# need to catch the error here if there is one.


	r_cmd_string = "setwd('" + rFileC + "')"
	me.eval(r_cmd_string)
	me.eval("Data<-ReadAffy()")
	me.eval("eset<-justRMA()")
	me.eval('write.exprs(eset, file="mydata.txt")')
	me.end()
	del(me)
	print "Finished RMA Computation\n"
	desktop.console.printPrompt()
	# check the last character
	rFile += "\mydata.txt"
	desktop.console.doInBackground('[E,Elabels,Explabels]=readmatrix("' + rFile +'",console.progressMan);E.varname="E";f=view(E);');
